<template>
  <view>
    <uni-nav-bar
      :fixed="true"
      :border="false"
      :statusBar="true"
      left-icon="left"
      color="#000"
      title="我的订单"
      backgroundColor="#fff"
      @clickLeft="handleBack"
    />
    <view class="my-order-tab">
      <u-tabs
        name="name"
        :height="100"
        style="width: 100%"
        bgColor="#fff"
        :showBar="true"
        :isScroll="false"
        tabBarColor="#C61323"
        active-color="#1F242E"
        inactive-color="#4E5969"
        :list="statusList"
        :current="curStatusIndex"
        @change="handleStatusChange"
      ></u-tabs>
    </view>
    <view class="my-order-list">
      <view
        class="my-order-item"
        v-for="order in orderList"
        :key="order.id"
        @click="toPage('/pages/order/order-detail?orderId=' + order.id)"
      >
        <view class="my-order-item-time-status">
          <view class="my-order-item-time">{{ order.createTime }}</view>
          <view class="my-order-item-status"> {{ order.orderStatusName }} </view>
        </view>
        <view class="my-order-item-goods" v-if="order.items && order.items.length > 0">
          <image
            class="my-order-item-goods-img"
            mode="aspectFill"
            :src="order.items[0].goodsCoverImg"
          />
          <view class="my-order-item-goods-name-num-intro-price">
            <view class="my-order-item-goods-name-num">
              <view class="my-order-item-goods-name">
                {{ order.items[0].goodsName }}
              </view>
              <view class="my-order-item-goods-num"> X{{ order.items[0].goodsCount }} </view>
            </view>
            <view class="my-order-item-goods-intro">
              {{ order.items[0].goodsIntro }}
            </view>
            <view class="my-order-item-goods-price">¥{{ order.items[0].sellingPrice }}</view>
          </view>
        </view>
        <view class="my-order-item-goods-bottom">
          <view class="my-order-item-goods-bottom-num-sum">
            <view class="my-order-item-goods-bottom-num"
              >共{{ order.items[0].goodsCount }}件商品</view
            >
            <view class="my-order-item-goods-bottom-sum"
              >实际支付 ¥{{ order.payPrice }} (含运费 ¥0)</view
            >
          </view>
          <view class="my-order-item-goods-bottom-btn">
            <view
              class="my-order-item-goods-bottom-btn-cancel"
              @tap.stop="handleCancelOrder(order)"
              v-if="order.orderStatus === 0"
              >取消订单</view
            >
            <view
              class="my-order-item-goods-bottom-btn-pay"
              @tap.stop="handlePayOrder(order)"
              v-if="order.orderStatus === 0"
              >去支付</view
            >
            <view
              class="my-order-item-goods-bottom-btn-pay"
              @tap.stop="handleReceiptOrder(order)"
              v-if="order.orderStatus === 2"
              >确认收货</view
            >
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';

import { WX_LOGIN_INFO } from '@/utils/constants.js';

import { setItem, getItem } from '@/utils/storage.js';

import { hideLoading, showLoading, showToast, toPage } from '@/utils/app';

import config from '@/api/config.js';

import { listOrder, receiptOrder, cancelOrder, createPrePayOrder } from '@/api/order.js';

import { getWxCodeInfo } from '@/api/wechat.js';

import { useUserInfoStore } from '@/stores/user';
const userInfoStore = useUserInfoStore();

const handleBack = () => {
  const pages = getCurrentPages();
  if(pages && pages.length > 1) {
    uni.navigateBack()
  } else {
    uni.switchTab({
      url: '/pages/index/user',
    })
  }
}

/**状态相关 */
const curStatusIndex = ref(0);
const curStatusId = ref(null);
const statusList = ref([
  {
    id: null,
    name: '全部',
  },
  {
    id: 0,
    name: '未付款',
  },
  {
    id: 2,
    name: '待领取',
  },
  {
    id: 3,
    name: '已完成',
  },
]);

const handleStatusChange = (index) => {
  if (curStatusIndex.value === index) {
    return;
  }
  curStatusIndex.value = index;
  curStatusId.value = statusList.value[index].id;
  listOrderOnRefresh();
};

const bindListener = () => {
  uni.$on('__orderRefresh__', function (data) {
    listOrderOnRefresh();
  });
};

onPullDownRefresh(() => {
  listOrderOnRefresh();
  setTimeout(function () {
    uni.stopPullDownRefresh();
  }, 800);
});

onMounted(() => {
  bindListener();
  listOrderOnRefresh();
});

// 上拉加载更多
onReachBottom(() => {
  if (orderHasMore.value) {
    const pageNo = orderPageNo.value + 1;
    listOrderReq(pageNo);
  }
});

const orderTotal = ref(0);
const orderPageNo = ref(1);
const orderHasMore = ref(false);
const orderList = ref([]);

const listOrderOnRefresh = () => {
  if (!userInfoStore.userId) {
    // uni.showModal({
    //   title: '',
    //   content: '您还未登录,无法查看订单信息',
    //   cancelText: '去首页',
    //   confirmText:'去登录',
    //   success: function (res) {
    //     if (res.confirm) {
    // handleLogin()
    //     } else if (res.cancel) {
    //       uni.switchTab({
    //         url: '/pages/index/mall'
    //       })
    //     }
    //   }
    // });
    return handleLogin();
  } else {
    orderPageNo.value = 1;
    orderHasMore.value = false;
    orderTotal.value = 0;
    listOrderReq(1);
  }
};

// 登录
const handleLogin = () => {
  uni.redirectTo({
    url: '/pages/user/wxLogin?fromPage=order',
  });
};

const listOrderReq = async (pageNo) => {
  const query = {
    pageNum: pageNo,
    pageSize: 20,
    userId: userInfoStore.userId,
  };
  if (curStatusId.value === 0 || curStatusId.value) {
    query['orderStatus'] = curStatusId.value;
  }
  const res = await listOrder(query);
  const rows = res.rows || [];
  if (pageNo > 1) {
    orderList.value.push(...rows);
  } else {
    orderList.value = rows;
  }
  orderTotal.value = res.total;
  if (res.total < 10) {
    orderHasMore.value = false;
  } else {
    orderHasMore.value = true;
  }
  orderPageNo.value = pageNo;
};

const handleCancelOrder = async (order) => {
  showLoading('...');
  const res = await cancelOrder(order.id);
  if (res.code === 200) {
    hideLoading();
    showToast('取消订单成功');
    listOrderOnRefresh();
  } else {
    hideLoading();
  }
};

const handlePayOrder = (order) => {
  toPage('/pages/order/order-detail?orderId=' + order.id);
};

const handleReceiptOrder = async (order) => {
  showLoading('...');
  const res = await receiptOrder(order.id);
  if (res.code === 200) {
    hideLoading();
    showToast('操作成功');
    listOrderOnRefresh();
  } else {
    hideLoading();
  }
};

onUnmounted(() => {
  uni.$off('__orderRefresh__');
});
</script>

<style scoped lang="scss">
.my-order-tab {
    width: 100%;
    position: fixed;
    z-index: 2;
  }

  .my-order-list {
    display: flex;
    flex-wrap: wrap;
    margin-top: 100rpx;
    padding-bottom: 50rpx;

    .my-order-item {
      width: 702rpx;
      margin: 24rpx 24rpx 0rpx 24rpx;
      padding: 24rpx;
      border-radius: 16rpx;
      background: #ffffff;
      display: flex;
      flex-direction: column;

      .my-order-item-time-status {
        display: flex;
        align-items: center;
        padding-bottom: 24rpx;
        border-bottom: 1rpx solid #e7eff2;

        .my-order-item-time {
          color: #545567;
          font-family: PingFang SC;
          font-size: 24rpx;
          flex: 1;
        }

        .my-order-item-status {
          color: #c61323;
          font-family: PingFang SC;
          font-weight: 500;
          font-size: 24rpx;
        }
      }

      .my-order-item-goods {
        padding: 24rpx 0rpx;
        display: flex;
        border-bottom: 1rpx solid #e7eff2;

        .my-order-item-goods-img {
          width: 170rpx;
          height: 170rpx;
          border-radius: 8rpx;
          background: #eeeeee;
        }

        .my-order-item-goods-name-num-intro-price {
          flex: 1;
          display: flex;
          flex-direction: column;
          margin-left: 16rpx;

          .my-order-item-goods-name-num {
            display: flex;

            .my-order-item-goods-name {
              color: #1f242e;
              font-family: PingFang SC;
              font-size: 26rpx;
              flex: 1;
            }

            .my-order-item-goods-num {
              margin-left: 24rpx;
              color: #828b94;
              font-family: PingFang SC;
              font-size: 24rpx;
            }
          }

          .my-order-item-goods-intro {
            margin-top: 8rpx;
            color: #828b94;
            font-family: PingFang SC;
            font-size: 24rpx;
          }

          .my-order-item-goods-price {
            color: #1f242e;
            font-family: DINPro;
            font-weight: 500;
            font-size: 36rpx;
            margin-top: 8rpx;
          }
        }
      }

      .my-order-item-goods-bottom {
        display: flex;
        flex-direction: column;
        margin-top: 24rpx;

        .my-order-item-goods-bottom-num-sum {
          display: flex;
          align-items: center;

          .my-order-item-goods-bottom-num {
            flex: 1;
            color: #828b94;
            font-family: PingFang SC;
            font-size: 26rpx;
          }

          .my-order-item-goods-bottom-sum {
            color: #1f242e;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 26rpx;
          }
        }

        .my-order-item-goods-bottom-btn {
          margin-top: 24rpx;
          display: flex;
          align-items: center;
          justify-content: flex-end;

          .my-order-item-goods-bottom-btn-cancel {
            width: 144rpx;
            height: 58rpx;
            border-radius: 16rpx;
            border: 1rpx solid #afb6bd;
            background: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #4e5969;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 24rpx;
            margin-right: 24rpx;
          }

          .my-order-item-goods-bottom-btn-pay {
            width: 120rpx;
            height: 58rpx;
            border-radius: 16rpx;
            background: linear-gradient(138.98deg, #cb3d3d 0.5%, #a11012 100.24%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #ffffff;
            font-family: PingFang SC;
            font-weight: 500;
            font-size: 24rpx;
          }
        }
      }
    }
  }
</style>
